//
//  FPCinemaViewController.m
//  FilmParadise
//
//  Created by lanou3g on 15/7/14.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//

#import "FPCinemaViewController.h"
#import "FPCinemaTableViewCell.h"
#import "FPCinemaCollectionViewCell.h"
#import "FPDetailCinemaTableViewController.h"
#import "FPCinemaModel.h"
#import "BMapKit.h"
#import "FPLocation.h"

@interface FPCinemaViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate,SDCycleScrollViewDelegate,BMKLocationServiceDelegate,BMKPoiSearchDelegate>
{
    BOOL _isClick;// 是否点击
    NSInteger _lblIndex;
    float _currentLatirude;
    float _currentLongitude;
}
@property (nonatomic, strong) NSArray *titleArray;// 存放标题
@property (nonatomic, strong) BMKPoiSearch *poisearch;
@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic, strong) NSMutableArray *nearbyCNameArray;
@property (nonatomic, strong) NSMutableArray *cinemaAddressArray;
@property (nonatomic, strong) NSMutableArray *currentDistanceArray;

@end

@implementation FPCinemaViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 创建collectionView
    [self B_collectionViewButton];
    //    [self search];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _locService.delegate = nil;
    _poisearch.delegate = nil;
    [_locService stopUserLocationService];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:view];
    
    
    // 创建tableView
    [self B_tableView];
    
    // 适配
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.0) {
        self.navigationController.navigationBar.translucent = NO;
    }
    
    //    [self getMothed];
    
}
/*=========================================方法实现=============================================*/

- (void)getMothed
{
    _poisearch = [[BMKPoiSearch alloc] init];
    _poisearch.delegate = self;
    
    _locService = [[BMKLocationService alloc] init];
    _locService.delegate = self;
    [_locService startUserLocationService];
}

// 用户位置更新后,会调用此函数
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    _currentLatirude = userLocation.location.coordinate.latitude;
    _currentLongitude = userLocation.location.coordinate.longitude;
}

- (void)search
{
    
    BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc] init];
    citySearchOption.pageIndex = 10;
    citySearchOption.city = [FPLocation shareInstance].cityLocal;
    citySearchOption.keyword = @"电影院";
    
    BOOL flag = [self.poisearch poiSearchInCity:citySearchOption];
    if (flag) {
        NSLog(@"城市内检索发送成功");
    }else
    {
        NSLog(@"城市内检索发送失败");
    }
}
/*=========================================创建视图=============================================*/
#pragma mark - 创建视图
// 创建collectionView
- (void)B_collectionViewButton
{
    self.titleArray = @[@"全部",@"附近",@"价格"];
    // 创建布局对象
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30) collectionViewLayout:layout];
    
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collectionView];
}

// 创建tableView
- (void)B_tableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, kScreenWidth, kScreenHeight -94) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = kImageH(90.0);
    
    self.tableView.tableHeaderView = [self buildScrollView];
    [self.view addSubview:_tableView];
}

// 轮播图
- (UIView *)buildScrollView
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 130)];
    
    NSArray *images = @[[UIImage imageNamed:@"lunbo1"],
                        [UIImage imageNamed:@"lunbo2"],
                        [UIImage imageNamed:@"lunbo3"],
                        [UIImage imageNamed:@"lunbo4"],
                        [UIImage imageNamed:@"lunbo5"]
                        ];
    CGFloat w = self.view.bounds.size.width;
    // 本地加载 --- 创建不带标题的图片轮播器
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, w, 132) imagesGroup:images];
    cycleScrollView.contentMode = UIViewContentModeScaleAspectFit;
    cycleScrollView.infiniteLoop = YES;
    cycleScrollView.delegate = self;
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    //    [self.view addSubview:cycleScrollView];
    // --- 轮播时间间隔，默认1.0秒，可自定义
    cycleScrollView.autoScrollTimeInterval = 1.5;
    [view addSubview:cycleScrollView];
    UIView *sepView = [[UIView alloc] initWithFrame:CGRectMake(0, 135, kScreenWidth, 5)];
    //    sepView.backgroundColor = [UIColor colorWithWhite:0.749 alpha:1.000];
    sepView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"xuxian"]];
    [view addSubview:sepView];
    
    return view;
}

/*====================================BMKSearch协议方法=======================================*/
#pragma mark -
#pragma mark implement BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
    
    if (error == BMK_SEARCH_NO_ERROR) {
        NSMutableArray *annotations = [NSMutableArray array];
        self.currentDistanceArray   = [NSMutableArray array];
        self.nearbyCNameArray       = [NSMutableArray array];
        self.cinemaAddressArray     = [NSMutableArray array];
        for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            item.coordinate = poi.pt;
            item.title = poi.name;
            BMKMapPoint point1 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake([FPLocation shareInstance].FPlatitude, [FPLocation shareInstance].FPlongitude));
            BMKMapPoint point2 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(poi.pt.latitude, poi.pt.longitude));
            CLLocationDistance distance = BMKMetersBetweenMapPoints(point1, point2);
            [self.currentDistanceArray addObject:[NSString stringWithFormat:@"%.1f",distance/1000]];
            [self.nearbyCNameArray addObject:poi.name];
            [self.cinemaAddressArray addObject:poi.address];
            [annotations addObject:item];
        }
        [self.tableView reloadData];
    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        NSLog(@"起始点有歧义");
    } else {
        // 各种情况的判断。。。
    }
}


/*============================================tableView===============================================*/
#pragma mark - 触发方法
/**
 *  轮播图点击触发方法
 *
 *  @param cycleScrollView 轮播图自动滚动
 *  @param index           轮播图的下标
 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", (long)index);
}

//- (void)btnAction:(UIButton *)button
//{
//    NSLog(@"点击了常去影院");
//}

/*============================================tableView===============================================*/
#pragma mark - tableView协议方法
// tableView有多少个分组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// 每个分组内有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _cinemaArray.count;
}

// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell1";
    [tableView registerClass:[FPCinema_TableViewCell class] forCellReuseIdentifier:cellIdentifier];
    FPCinema_TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    FPCinemaModel *model         = self.cinemaArray[indexPath.row];
    
    FPCinemaModel *feature       = self.featureArray[indexPath.row];
    
    //----------------------------------------------------------------
    NSMutableArray *distanceArray= [self sequenceByDistance];
    FPCinemaModel *distanceModel = distanceArray[indexPath.row];
    //----------------------------------------------------------------
    
    NSMutableArray *priceArray   = [self sequenceByPrice];
    FPCinemaModel *priceModel    = priceArray[indexPath.row];
    if (_lblIndex == 0) {
        
        [cell cellInitWithModel:model];
        
        [cell cellInitWithshowFeature:feature];
    }
    if (_lblIndex == 1) {
        [cell cellInitWithModel:distanceModel];
        
        //        if ([distanceModel.cinameName isEqualToString:model.cinameName]) {
        //            [cell cellInitWithshowFeature:feature];
        //        }
    }
    if (_lblIndex == 2) {
        
        [cell cellInitWithModel:priceModel];
        
        //        if ([_cinemaArray containsObject:priceModel.cinameName]) {
        //            [cell cellInitWithshowFeature:feature];
        //        }
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

// tableView点击cell方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FPDetailCinemaTableViewController *fpDetailCinemaTC = [[FPDetailCinemaTableViewController alloc] init];
    if (_lblIndex == 0) {
        FPCinemaModel *model  = self.cinemaArray[indexPath.row];
        fpDetailCinemaTC.kUrl = [NSString stringWithFormat:@"%ld",(long)model.cinemaId];
        fpDetailCinemaTC.distance = model.distance;
    }
    if (_lblIndex == 1) {
        NSMutableArray *distanceArray = [self sequenceByDistance];
        FPCinemaModel *distanceModel  = distanceArray[indexPath.row];
        fpDetailCinemaTC.kUrl         = [NSString stringWithFormat:@"%ld",(long)distanceModel.cinemaId];
        fpDetailCinemaTC.distance     = distanceModel.distance;
    }
    if (_lblIndex == 2) {
        NSMutableArray *array             = [self sequenceByPrice];
        FPCinemaModel *priceModel         = array[indexPath.row];
        fpDetailCinemaTC.kUrl = [NSString stringWithFormat:@"%ld",(long)priceModel.cinemaId];
        fpDetailCinemaTC.distance         = priceModel.distance;
    }
    [self.navigationController pushViewController:fpDetailCinemaTC animated:YES];
}

// 数组根据价钱排序
- (NSMutableArray *)sequenceByPrice
{
    NSMutableArray *array = [_cinemaArray mutableCopy];
    //    [array addObjectsFromArray:_cinemaArray];
    [array sortUsingComparator:^NSComparisonResult(FPCinemaModel *obj1, FPCinemaModel *obj2) {
        if (obj1.minPrice == 0) {
            obj1.minPrice = 1000;
        }
        if (obj2.minPrice == 0) {
            obj2.minPrice = 2000;
        }
        if(obj1.minPrice > obj2.minPrice){
            return NSOrderedDescending;
        }
        else if(obj1.minPrice == obj2.minPrice){
            return NSOrderedSame;
        }else{
            return NSOrderedAscending;
        }
        
    }];
    
    return array;
}

// 根据距离排序
- (NSMutableArray *)sequenceByDistance
{
    NSMutableArray *array = [NSMutableArray array];
    [array addObjectsFromArray:_cinemaArray];
    //    array = [_cinemaArray mutableCopy];
    [array sortUsingComparator:^NSComparisonResult(FPCinemaModel *obj1, FPCinemaModel *obj2) {
        if ([obj1.distance intValue] > [obj2.distance intValue]) {
            return NSOrderedDescending;
        }
        else if ([obj1.distance intValue] == [obj2.distance intValue]){
            return NSOrderedSame;
        }else{
            return NSOrderedAscending;
        }
    }];
    return array;
}

/*=========================================collectionView=============================================*/
#pragma mark - collectionView协议方法
// 返回cell宽和高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kScreenWidth / 3 - 7, 30);
}

// 一共多少个分组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

// 每个分组多少个item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _titleArray.count;
}

#pragma mark - 返回cell
// 返回collectionViewCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell2";
    [collectionView registerClass:[FPCinemaCollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
    FPCinemaCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    
    cell.label.text = self.titleArray[indexPath.item];
    
    if (_isClick == YES) {
        (indexPath.item == _lblIndex) ? (cell.label.backgroundColor = [UIColor grayColor]) : (cell.label.backgroundColor = [UIColor whiteColor]);
    }else{
        (indexPath.item == 0) ? (cell.label.backgroundColor = [UIColor grayColor]) : (cell.label.backgroundColor = [UIColor whiteColor]);
    }
    
    return cell;
}

// collection点击cell方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    _isClick = NO;
    for (FPCinemaCollectionViewCell *cell in collectionView.visibleCells) {
        cell.label.backgroundColor = [UIColor whiteColor];
    }
    _lblIndex = indexPath.row;
    _isClick = YES;
    FPCinemaCollectionViewCell *cell = (FPCinemaCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.label.backgroundColor = [UIColor grayColor];
    
    switch (indexPath.row) {
        case 0:
            // 显示所有信息
            NSLog(@"全部");
            [self.tableView reloadData];
            break;
        case 1:
            // 显示附近电影院
            NSLog(@"附近");
            [self.tableView reloadData];
            break;
        case 2:
            // 显示价格
            NSLog(@"价格");
            [self.tableView reloadData];
            break;
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
